<template>
  <div class="interview">
    <!-- 顶部 -->
    <div class="header">
      <!-- 导航栏 -->
      <van-nav-bar left-arrow fixed @click-left="onClickLeft">
        <template #title>
          <!-- 标题 -->
          <span class="custom-title"
            >面试题
            <span class="num">{{ questionList.length }}</span>
          </span>
        </template>
        <template #left>
          <i class="iconfont iconbtn_nav_back"></i>
        </template>
        <template #right>
          <span v-if="isReady" style="color: #969799;">答题卡</span>
          <span @click="onClickRight" v-else>答题卡</span>
        </template>
      </van-nav-bar>
      <!-- 选择栏 -->
      <div class="filter-box" v-if="$route.query.company !== undefined">
        <div class="scroll-wrap">
          <div class="content">
            <van-tag
              type="primary"
              round
              :class="{ active: currentId === index }"
              v-for="(item, index) in getjobList"
              :key="index"
              @click="checkjob(index)"
              >{{ item }}</van-tag
            >
          </div>
        </div>
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="city"
            :options="getCityList"
            title="城市"
            lazy-render
            :disabled="hadQue"
            @change="checkCity"
          />
          <van-dropdown-item
            v-model="potision"
            :options="getPotision"
            title="岗位"
            lazy-render
            :disabled="hadQue"
          />
          <van-dropdown-item
            v-model="difficulty"
            :options="difficultyList"
            title="难度"
            :disabled="hadQue"
          />
        </van-dropdown-menu>
      </div>
    </div>
    <!-- 答题组件 -->
    <ans
      :questionItem="questionList[currentQuestion]"
      @check="check"
      ref="ans"
      v-if="questionList.length !== 0"
    />
    <div class="bottom">
      <div class="companybtn" v-if="isReady">
        <div></div>
        <van-button type="primary" size="normal" @click="getCompanyQus"
          >开始</van-button
        >
      </div>
      <div class="ansbtn" v-else>
        <!-- 左边字体图标 -->
        <div class="left">
          <span :class="isCollect()"
            ><i class="iconfont iconbtn_shoucang_nor" @click.stop="collect"></i>
            收藏
          </span>
          <span
            ><i
              class="iconfont iconbtn_shuati_fankui"
              @click.stop="show = true"
            ></i>
            反馈
          </span>
        </div>
        <div class="middle">
          <span>{{ currentQuestion + 1 }}</span
          >/{{ questionList.length }}题
        </div>
        <div class="right">
          <div v-if="!finish">
            <van-button
              :disabled="questionList[currentQuestion].check"
              type="danger"
              size="normal"
              v-if="!questionList[currentQuestion].itemFinish"
              @click="submit"
              >提交
            </van-button>
            <van-button type="info" size="normal" v-else @click="nextQuestion"
              >下一题</van-button
            >
          </div>
          <div v-else>
            <van-button type="danger" size="normal" @click="end"
              >结束</van-button
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 弹出层答题卡 -->
    <card
      ref="card"
      :questionList="questionList"
      :currentQuestion.sync="currentQuestion"
      @getQueItem="getQueItem"
      v-if="questionList.length !== 0"
    />
    <!-- 反馈页面 -->
    <van-dialog
      class="feedback"
      v-model="show"
      show-cancel-button
      @confirm="confirm"
    >
      <template #title>
        <h3>意见反馈</h3>
      </template>
      <van-field
        v-model="message"
        rows="2"
        type="textarea"
        placeholder="请输入你对此题的反馈意见"
        show-word-limit
      />
    </van-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { getLocal } from '@/utils/local.js'
import {
  questionDetail,
  submitQuestion,
  collectQuestion,
  questionFilters,
  companyQuestion
} from '@/api/api.js'
export default {
  computed: {
    ...mapState({
      questionList: state => state.questionList,
      userInfo: state => state.userInfo
    }),
    finish () {
      var falg = true
      for (var i = 0; i < this.questionList.length; i++) {
        if (!('subimt' in this.questionList[i])) {
          falg = false
        }
      }
      return falg
    },
    getjobList () {
      return this.allList.map(item => item[0]) || []
    },
    getCityList () {
      if (this.allList[this.currentId] !== undefined) {
        return this.allList[this.currentId][1]
      } else {
        return []
      }
    },
    getCurrentCity () {
      return (
        this.getCityList.filter(item => {
          return item.value === this.city
        }) || []
      )
    },
    getPotisionList () {
      return this.getCurrentCity[0] || {}
    },
    getPotision () {
      return this.getPotisionList.positions || []
    }
  },
  data () {
    return {
      currentQuestion: null,
      isReady: false,
      isans: true,
      type: 1,
      isFinish: false,
      singleAnswer: '', // 单选题答案
      multipleAnswer: [], // 多选题答案
      show: false,
      message: '', // 反馈信息
      currentId: 0,
      city: 0, // 城市
      potision: 0, // 职业
      difficulty: 0,
      difficultyList: [
        { text: '不限', value: 0 },
        { text: '简单', value: 1 },
        { text: '中等', value: 2 },
        { text: '困难', value: 3 }
      ],
      allList: [], // 计算的依赖项
      hadQue: false,
      timer: 0 // 防抖
    }
  },
  methods: {
    // 映射试题的方法
    ...mapMutations(['SETCOLLECTQUESTIONS', 'CLEARQUESTION', 'SETQUESTION']),
    onClickLeft () {
      // 左边的点击按钮
      this.$dialog
        .confirm({
          title: '确认退出？',
          message: '下次重新开始刷题哦'
        })
        .then(() => {
          this.$router.back()
          setTimeout(() => {
            this.CLEARQUESTION()
          }, 100)
        })
        .catch(() => {})
    },
    onClickRight () {
      // 右边的点击按钮
      this.$refs.card.show = true
    },
    async getQueItem (item) {
      try {
        this.$refs.ans.radio = ''
        this.$refs.ans.result = []
      } catch (error) {}
      // 如果已经有试题的详情了,则不再发送axios
      if (this.questionList[this.currentQuestion].item) {
        if (this.$refs.card !== undefined) {
          this.$refs.card.show = false
        }
        return
      }
      // 得到试题详情
      this.$set(this.questionList[this.currentQuestion], 'itemFinish', false)
      const res = await questionDetail(item.id)
      this.$set(this.questionList[this.currentQuestion], 'item', res.data)
      if (this.questionList[this.currentQuestion].item.type === 3) {
        this.$set(this.questionList[this.currentQuestion], 'check', false)
      } else {
        this.$set(this.questionList[this.currentQuestion], 'check', true)
      }
      if (this.$refs.card !== undefined) {
        this.$refs.card.show = false
      }
    },
    check (a, b) {
      // 选中试题
      if (a.length !== 0 || b.length !== 0) {
        // 两者中有一个有答案
        this.$set(this.questionList[this.currentQuestion], 'check', false)
        this.singleAnswer = a
        this.multipleAnswer = b
      } else {
        this.$set(this.questionList[this.currentQuestion], 'check', true)
      }
    },
    async submit () {
      var res
      // 提交按钮
      if (this.questionList[this.currentQuestion].item.type === 1) {
        // 单选题提交答案
        this.$set(
          this.questionList[this.currentQuestion],
          'userSing',
          this.singleAnswer
        )
        res = await submitQuestion({
          id: this.questionList[this.currentQuestion].id,
          singleAnswer: this.singleAnswer
        })
        this.$set(
          this.questionList[this.currentQuestion],
          'singleAnswer',
          res.data.singleAnswer
        )
      } else if (this.questionList[this.currentQuestion].item.type === 2) {
        // 多选题提交答案
        this.$set(
          this.questionList[this.currentQuestion],
          'userMult',
          this.multipleAnswer
        )
        res = await submitQuestion({
          id: this.questionList[this.currentQuestion].id,
          multipleAnswer: this.multipleAnswer
        })
        this.$set(
          this.questionList[this.currentQuestion],
          'multipleAnswer',
          res.data.multipleAnswer
        )
      } else {
        // 简答题提交答案
        res = await submitQuestion({
          id: this.questionList[this.currentQuestion].id
        })
      }
      this.$set(this.questionList[this.currentQuestion], 'subimt', res.data)
      this.$set(
        this.questionList[this.currentQuestion],
        'isRight',
        res.data.isRight
      )
      this.$set(this.questionList[this.currentQuestion], 'itemFinish', true)
      if (this.questionList[this.currentQuestion].item.type !== 3) {
        if (res.data.isRight) {
          this.$toast.success('恭喜您答对啦!')
        } else {
          this.$toast.fail('好可惜,差一点点哦')
        }
      } else {
        this.$toast.fail('简单功能正在完善中,您可以先看看答案哦!')
      }
    },
    // 下一题
    nextQuestion () {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.singleAnswer = ''
        this.multipleAnswer = []
        if (this.questionList[this.currentQuestion].item === undefined) {
          // 题目还没出现，不能点击
          return
        }
        if (this.currentQuestion < this.questionList.length - 1) {
          this.currentQuestion++
          this.getQueItem({ id: this.questionList[this.currentQuestion].id })
        } else {
          this.$dialog
            .alert({
              title: '提示',
              message: '还有题目没答哦，记得检查一下答题卡'
            })
            .then(() => {})
        }
      }, 1000)
    },
    // 结束按钮
    end () {
      this.$dialog
        .alert({
          title: '提示',
          message: '答完了，你真棒'
        })
        .then(() => {
          this.$router.back()
          setTimeout(() => {
            this.CLEARQUESTION()
          }, 100)
        })
    },
    // 确认反馈按钮
    confirm () {
      this.$toast.fail('反馈功能正在加班开发中哦')
    },
    // 获取是否已被收藏的样式
    isCollect () {
      if (
        this.userInfo.collectQuestions.includes(
          this.questionList[this.currentQuestion].id
        )
      ) {
        return 'collect'
      }
    },
    // 收藏试题
    async collect () {
      const res = await collectQuestion({
        id: this.questionList[this.currentQuestion].id
      })
      this.SETCOLLECTQUESTIONS(res.data)
      if (
        this.userInfo.collectQuestions.includes(
          this.questionList[this.currentQuestion].id
        )
      ) {
        this.$toast.success('收藏成功')
      } else {
        this.$toast.fail('已取消收藏')
      }
    },
    // 点击上方切换职业条件
    checkjob (index) {
      if (!this.hadQue) {
        this.currentId = index
        this.city = this.getCityList[0].value
        this.potision = this.getPotision[0].value
      }
    },
    // 点击城市
    checkCity () {
      this.potision = this.getPotision[0].value
    },
    // 获取企业面试题
    async getCompanyQus () {
      const res = await companyQuestion({
        id: this.$route.query.company,
        position: this.potision,
        difficulty: this.difficulty
      })
      if (res.data.length !== 0) {
        this.SETQUESTION(res.data)
        this.isReady = false
        this.currentQuestion = 0
        this.getQueItem({ id: this.questionList[this.currentQuestion].id })
        this.hadQue = true
      } else {
        this.$toast.fail('该分类的面试题还没有收录,请重新选择')
      }
    }
  },
  components: {
    card: () => import('./card'),
    ans: () => import('./ans')
  },
  async created () {
    if (!getLocal('heimamm_mobile_token')) {
      this.$router.push('/checklogin')
    }
    // 根据试题的长度来判断
    if (this.questionList.length !== 0) {
      // 试题长度不等于0
      this.isReady = false
      this.currentQuestion = 0
      this.getQueItem({ id: this.questionList[this.currentQuestion].id })
    } else {
      // 试题长度等于0
      this.isReady = true
      this.currentQuestion = null
      if (this.$route.query.company !== undefined) {
        // 获取企业的筛选条件
        const res = await questionFilters(this.$route.query.company)
        this.allList = res.data
        this.checkjob(0)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.interview {
  .header {
    background-color: #fff;
    margin-top: 46px;
    box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.17);
    /deep/.van-ellipsis {
      overflow: visible !important;
      /deep/.custom-title {
        position: relative;
        .num {
          position: absolute;
          top: -5px;
          right: -18px;
          font-size: 12px;
          color: #545671;
        }
      }
    }
    .iconbtn_nav_back {
      font-size: 44px;
      line-height: 44px;
      transform: translateX(-10px);
    }
    .scroll-wrap {
      width: 100%;
      overflow-x: scroll;
      &::-webkit-scrollbar {
        display: none;
      }
      .content {
        padding: 15px;
        display: flex;
        height: 59px;
        .van-tag {
          padding: 6px 12px;
          flex-shrink: 0;
          margin-right: 10px;
          background: #f7f4f5;
          color: #545671;
        }
        .van-tag.active {
          background: #00b8d4;
          color: #fff;
        }
      }
    }
  }
  .bottom {
    height: 85px;
    position: fixed;
    left: 0;
    width: 100%;
    bottom: 0;
    padding-top: 11px;
    background-color: #fff;
    .ansbtn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 15px;
      .left {
        display: flex;
        span {
          font-size: 0.32rem;
          color: #b4b4bd;
          margin-right: 0.56rem;
          &.collect {
            color: #e40137;
            i {
              color: #e40137;
            }
          }
          i {
            display: block;
            font-size: 0.74667rem;
            color: #b4b4bc;
          }
        }
      }
      .middle {
        font-size: 14px;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        span {
          font-size: 22px;
          color: #d12d3e;
        }
      }
      /deep/ .van-button {
        width: 98px;
        height: 40px;
        border-radius: 4px;
      }
    }
    .companybtn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 15px;
      div {
        flex: 1;
      }
      /deep/ .van-button {
        width: 98px;
        height: 40px;
        border-radius: 4px;
      }
    }
  }
  .feedback {
    /deep/ .van-dialog__header {
      padding-top: 0;
    }
    /deep/ .van-field__control {
      width: 264px;
      height: 165px;
      background: #f7f4f5;
      border-radius: 8px;
      transform: translateX(14px);
    }
  }
}
</style>
